<?php 

define("FETCH_MODE_NONE", -1);
define("FETCH_MODE_CELL",0);
define("FETCH_MODE_ROW",1);
define("FETCH_MODE_COLUMN",2);
define("FETCH_MODE_TABLE",3);

global $page;
global $mode;
global $login;
global $filename;

class Db
{
	private static $_link;
	
	static function mysql_query($query,$fetch_mode)
	{
		Db::mysql_connect();
		$result = mysql_query($query);
		if (!$result) 
		{
			die('Invalid query: ' . mysql_error());
		}
		switch($fetch_mode)
		{
			case FETCH_MODE_ROW:
				if($row=mysql_fetch_assoc($result))
					return $row;
				break;
			case FETCH_MODE_CELL:
				if($row=mysql_fetch_row($result))
					return $row[0];						
				break;
			case FETCH_MODE_TABLE:
				$table=array();
				while($row=mysql_fetch_assoc($result))
					$table[]=$row;
				return $table;
				break;
			case FETCH_MODE_COLUMN:
				$array=array();
				while($row=mysql_fetch_row($result))
					$array[]=$row[0];
				return $array;
				break;
			case FETCH_MODE_NONE:
				return true;
				break;
		}
		return null;
	}
	
	static function mysql_connect()
	{
		if(Db::$_link==null)
		{
			$link = mysql_connect(SVR, USN, PWD);
			if (!$link) 
			{
				die('Could not connect: ' . mysql_error());
			}
			$db_selected = mysql_select_db(DTB, $link);
			if (!$db_selected) 
			{
				die ('Can\'t use db : ' . mysql_error());
			}
			mysql_set_charset('utf8',$link); 
			Db::$_link=$link;
		}
	}
	
	static function mysql_close()
	{
		if(Db::$_link!=null)
			mysql_close(Db::$_link);
	}
}

class Partial
{
	/*static public function create_toolbar_items_level_2($items)
	{
		$string='';
		foreach($items as $item)
			$string.=Page::create_toolbar_item_level_2($item);
		return $string;
	}*/
	
	static public function paginator($link,$row_per_page,$query)
	{
		$i=isset($_GET['i'])?$_GET['i']:1;
		$count=Db::mysql_query($query, FETCH_MODE_CELL);
	?> 
		<div id='pagination'>
			<?php if($i>1){?><span class='direct' id='prev' onclick="window.location='<?php echo $link;?>&i=<?php echo $i-1?>'">Trang trước</span><?php }?>
					
			<?php 		
			$min=$i-5;
			$max=$i+4;
			if(ceil($count/$row_per_page)<10)
			{
				$min=1;
				$max=ceil($count/$row_per_page);				
			}
			else if($min<1)
			{
				$max+=(0-$min+1);
				$min=1;
			}
			else if($max>ceil($count/$row_per_page))
			{
				$min-=($max-ceil($count/$row_per_page));
				$max=ceil($count/$row_per_page);
			}
			?>
			
			<?php for($j=$min;$j<=$max;$j++){?>
				<?php if($i==$j){?>
				<span class='number' id='current'><?php echo $j;?></span>
				<?php }else{?>
				<span class='number' onclick="window.location='<?php echo $link?>&i=<?php echo $j?>'" ><?php echo $j;?></span>
				<?php }?>
			<?php }	?> 
			
			<?php if($i<ceil($count/$row_per_page)){?><span class='direct' onclick="window.location='<?php echo $link?>&i=<?php echo $i+1?>'" id='next'>Trang tiếp theo</span><?php }?>
		</div>
	<?php 
	}
	
	static public function create_toolbar_item_level_2($label_1,$link_1,$label_2,$link_2,$title_2,$label_3='',$link_3='',$title_3='')
	{
		$string="
		<li>
			<a style='margin-left:48px' href='$link_1'>
				<span>$label_1</span>
			</a>
			<a class='first' href='$link_2' title='$title_2'>
				<span class='process'>$label_2</span>
			</a>";
		if($title_3!='')
		{
			$string.="
			<a class='second' href=\"javascript:if(confirm('Bạn có đồng ý xóa mục tin này không?')){window.location='$link_3'}\" title='".LDELETE."'>
				<span class='process'>".LDELETE_LABEL."</span>
			</a>";
		}
		$string.="</li>";
		return $string;
	}
	
	static public function create_toolbar_item_level_1($label_1,$link_1,$label_2,$link_2,$title_2)
	{
		$string='
		<li>
			<a href="'.$link_1.'"><span>'.$label_1.'</span></a>
			<a href="'.$link_2.'" title="'.$title_2.'"><span class="process">'.$label_2.'</span></a>
		</li>';
		return $string;
	}
	
	static public function create_menu_item($page_code)
	{		
		$page_title=Common::fetch_constant_by_string($page_code);
		$string="
		<li>
			<a href='index.php?page=$page_code'>
				$page_title
			</a>
		</li>";
		return $string;
	}
	
	static public function print_page_1($title,$content,$link)
	{
		$string="
		<div class='sub_header'>$title</div>
		<div class='i-update' link='$link'>	
			$content
		</div>";
		return $string;
	} 
}

class Config
{
	static public function fetch_by_name($config_name,$offline=1)
	{
		if($offline==1 && Config::is_exists_in_session($config_name,$row))
			return $row;
		$query="SELECT * FROM tbl_config WHERE config_name='$config_name' ";
		$row=Db::mysql_query($query,FETCH_MODE_ROW);
		Config::save_to_session($row);
		return $row;
	}
	
	static public function save_by_name($config_name,$config_value_type,$config_content)
	{
		$config_content=addslashes($config_content);
		$query="UPDATE tbl_config SET config_content='$config_content' WHERE config_name='$config_name' ";
		Db::mysql_query($query,FETCH_MODE_NONE);
		return Config::fetch_by_name($config_name,0);
	}
	
	static public function is_exists_in_session($config_name,&$row=null)
	{
		if(isset($_SESSION['config'][$config_name]))
		{
			$row=$_SESSION['config'][$config_name];
			return true;
		}
		return false;
	}
	
	static public function save_to_session($row)
	{
		$config_name=$row['config_name'];
		$_SESSION['config'][$config_name]=$row;
	}
	
	static public function fetch_config_content_by_name($config_name)
	{
		$row=Config::fetch_by_name($config_name);
		if($row)
			return Common::escape($row['config_content'],$row['config_value_type']);
		return null;
	}
}

class Page
{
	static public function fetch_group_alias_from_group_id($page_group_id)
	{
		switch ($page_group_id)
		{
			case 3:
				return 'tin-tuc';
			case 4:
				return 'dich-vu';
			case 5:
				return 'thue';
			default:
				Common::header_location(null,'error.php?code=404');
		}
	}
	
	static public function fetch_by_id($page_id)
	{
		$query="SELECT * FROM tbl_page WHERE page_id='$page_id' ";
		return Db::mysql_query($query,FETCH_MODE_ROW);
	}
	
	static public function fetch_page_group_id_by_id($page_id)
	{
		$row=Page::fetch_by_id($page_id);
		if($row)
			return $row['page_group_id'];
		return null;
	}
	
	static public function save_by_id($page_id=null,$page_group_id,$array=array())
	{
		if($page_id==null)
		{
		}
		else
		{
			if(isset($array['page_title']))
				$array['page_alias']=Common::no_mark($array['page_title']);			
			$tmp="";
			foreach($array as $k=>$v)
				if(isset($v))
				{
					if($tmp!='')
						$tmp.=',';
					$v=addslashes($v);
					$tmp.= " `$k`='$v' ";
				}
			$query="UPDATE tbl_page SET $tmp WHERE page_id='$page_id' "; 
			return Db::mysql_query($query,FETCH_MODE_NONE);		
		}		
	}
}

class Common
{	
	/*static function check_auth()
	{
		global $login;
		global $page;
		$check_pages=array('_change-password','_delete','_insert','_mode','_update-by-id','_update-by-name','_update-class','_update-news');
		if($login==0 && in_array($page,$check_pages))
		{
			Common::header_location(null,'index.php?page=_login');
			return 0;
		}
		return 1;
	}*/
	
	static public function fetch_message_from_code($code)
	{
		switch($code)
		{
			case 408:$message='Request Timeout';break;
			case 404:$message='Not Found';break;
			case 403:$message='Forbidden';break;
			default:$message='';break;
		}
		return $message;
	}
	
	static public function escape($value,$type)
	{
		switch($type)
		{
			case 1://textarea editor Full
				break;
			case 2://input type text
				break;
			case 3://textarea
				$value=nl2br($value);
				break;
		}
		return $value;
	}
	
	static public function define_var_from_array($array,$array_name='row')
	{
		$string='';
		foreach($array as $k=>$v)
			$string.="\$".$k."=\$".$array_name."['".$k."'];";
		return $string;
	}
	
	static public function fetch_record_start($row_per_page)
	{
		$i=isset($_GET['i'])?$_GET['i']:1;
		return ($i-1)*$row_per_page;
	}
	
	static public function fetch_constant_by_string($string)
	{
		$tmp_page_name=$string;
		if($tmp_page_name[0]=='_')
			$tmp_page_name=substr($tmp_page_name,1);
		$tmp_page_name=str_replace('-','_',$tmp_page_name);
		$tmp_page_name="L".strtoupper($tmp_page_name);
		$constant='';
		eval("if(defined('$tmp_page_name')) {\$constant=$tmp_page_name;}");
		return $constant;
	}
	
	static function header_location($message=null,$url=null,$script_afer_alert="")
	{
		if($url==null)
			$url_script='';
		else if(is_numeric($url))
			$url_script="history.go($url);";
		else
			$url_script="window.location='$url';" ;
		$message_script=$message==null?'':"alert('$message');";		
		if($message_script=='' && $script_afer_alert=='' && !is_numeric($url))
		{
			$script="<script> $message_script $url_script </script>";
			die($script);
		}
		else if($message_script!="" && $url_script!='') 
		{
			$script="<script> $message_script $url_script </script>";
			die($script);
		}
		else
		{
			$script="<script>$(document).ready(function(){ $message_script $script_afer_alert });</script>";
			echo ($script);
		}
	}
	
	static function get_image_path($string)
	{
		return BASE_URL.$string;
	}
	
	static function get_thumb_path($string)
	{
		$string=str_replace('/images/','/_thumbs/images/',$string);
		return Common::get_image_path($string);
	}
	
	static function no_mark($string,$separator='',$replace_char='')
	{
		$separator=$separator==''?'-':$separator;
		$replace_char=$replace_char==''?' ':$replace_char;
		if ($string != '')
		{
			$string = trim ( $string );
			$string = preg_replace ( '/\s\s+/', ' ', $string );
			$string = str_replace ( array ("\r\n", "\r", "\t", "\n" ), ' ', $string );
			$string = mb_convert_case ( $string, MB_CASE_LOWER, 'utf-8' );
			$chars = array ('a' => array ('a', 'á', 'à', 'ả', 'ạ', 'ã', 'â', 'ấ', 'ầ', 'ẩ', 'ậ', 'ẫ', 'ă', 'ắ', 'ằ', 'ẳ', 'ặ', 'ẵ' ), 
						'b' => array ('b' ), 
						'c' => array ('c' ), 
						'd' => array ('d', 'đ' ), 
						'e' => array ('e', 'é', 'è', 'ẻ', 'ẹ', 'ẽ', 'ê', 'ế', 'ề', 'ể', 'ệ', 'ễ' ), 
						'f' => array ('f' ), 
						'g' => array ('g' ), 
						'h' => array ('h' ), 
						'j' => array ('j' ), 
						'k' => array ('k' ), 
						'l' => array ('l' ), 
						'm' => array ('m' ), 
						'n' => array ('n' ), 
						'i' => array ('i', 'í', 'ì', 'ỉ', 'ị', 'ĩ' ), 
						'o' => array ('o', 'ó', 'ò', 'ỏ', 'ọ', 'õ', 'ơ', 'ớ', 'ờ', 'ở', 'ợ', 'ỡ', 'ô', 'ố', 'ồ', 'ổ', 'ộ', 'ỗ' ), 
						'u' => array ('u', 'ú', 'ù', 'ủ', 'ụ', 'ũ', 'ư', 'ư', 'ừ', 'ử', 'ự', 'ữ' ), 
						'y' => array ('y', 'ý', 'ỳ', 'ỵ', 'ỷ', 'ỹ' ), 
						'q' => array ('q' ), 
						'w' => array ('w' ), 
						'r' => array ('r' ), 
						't' => array ('t' ), 
						'p' => array ('p' ), 
						's' => array ('s' ), 
						'z' => array ('z' ), 
						'x' => array ('x' ), 
						'v' => array ('v' ) );
			foreach ( $chars as $k => $v )
				$string = str_replace ( $v, $k, $string );
			if ($separator != '')
				$string = str_replace ( $replace_char, $separator, $string );
			$string = preg_replace ( '/[^a-z0-9\s-.]/i', NULL, $string );
		}
		return $string;
	}
	
	static function init()
	{	
		//
		global $page;
		global $mode;
		global $login;
		global $filename;
		
		//
		require_once "php/config.php";
		
		//
		session_start();
		if(!isset($_SESSION['base_url']))
			$_SESSION['base_url']=BASE_URL;
		if(!isset($_SESSION['login']))
			$_SESSION['login']=0;
		if(!isset($_SESSION['mode']))		
			$_SESSION['mode']='view';
		if(!isset($_SESSION['config']))
			$_SESSION['config']=array();
		$login=$_SESSION['login'];
		$mode=$_SESSION['mode'];
		$base_url=$_SESSION['base_url'];
		$filename=basename($_SERVER['PHP_SELF']);
		
		//
		require_once "php/lib/constant.php";
		
		//
		$page=isset($_GET['page'])?$_GET['page']:DEFAULT_PAGE;
	}
}

Common::init();
?>


